package api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

public class getToken implements APIKey {
	public String getAuth(String flag) {
		switch (flag) {
		case "face":
			return getTextAuth(clientFaceId, clientFaceSecret);
		case "text":
			return getTextAuth(clientTextId, clientTextSecret);
		default:
			break;
		}
		return null;

	}

	public static void main(String[] args) {
		String getAccessTokenUrl = "http://api.syhuo.net/oauth2/get_token_info"
				+ "?access_token=9e3b2f34ddbc5a9e12aed02ca19450514092737e";
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			Map<String, List<String>> map = connection.getHeaderFields();
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			System.err.println("result:" + result);
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
		} catch (Exception e) {
			System.err.printf("获取token失败");
			e.printStackTrace(System.err);
		}
	}

	/**
	 * 获取token
	 * 
	 * @param ak
	 * @param sk
	 * @return
	 */
	private String getTextAuth(String ak, String sk) {
		String getAccessTokenUrl = authHost + "grant_type=client_credentials" + "&client_id=" + ak + "&client_secret="
				+ sk;
		try {
			URL realUrl = new URL(getAccessTokenUrl);
			HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
			connection.setRequestMethod("GET");
			connection.connect();
			Map<String, List<String>> map = connection.getHeaderFields();
			for (String key : map.keySet()) {
				System.err.println(key + "--->" + map.get(key));
			}
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String result = "";
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			System.err.println("result:" + result);
			JSONObject jsonObject = new JSONObject(result);
			String access_token = jsonObject.getString("access_token");
			return access_token;
		} catch (Exception e) {
			System.err.printf("获取token失败");
			e.printStackTrace(System.err);
		}
		return null;
	}
}
